//
//  Connection.m
//  mUBB
//
//  Created by Cosmin Stirbu on 1/13/13.
//  Copyright (c) 2013 Cosmin Stirbu. All rights reserved.
//

#import "Connection.h"
#import "Constants.h"
#import "Utils.h"

@implementation Connection

@synthesize  connectionDelegate;

- (id)initWithRequest:(NSURLRequest *)_request delegate:(ConnectionDelegate *)_delegate {
    self = [super initWithRequest:_request delegate:self];
    [self setConnectionDelegate:_delegate];
    return self;
}

- (void)executeRequest {
    // Log the request
    NSString *httpMethod = [self.currentRequest HTTPMethod];
    NSString *url = [self.currentRequest.URL absoluteString];
    NSString *authorization = [self.currentRequest valueForHTTPHeaderField:@"Authorization"];
    NSString *body = [[NSString alloc] initWithData:[self.currentRequest HTTPBody] encoding:NSUTF8StringEncoding];
    NSLog(@"### %@ with url:%@\nand Authorization:%@ \nBody:[%@]", httpMethod, url, authorization, body);
    // Display activity indicator
    [Utils showNetworkActivityIndicator];
    
    // Start connection
    [self start];
}

#pragma mark - NSURLConnectionDelegate methods

// Automatically accept challenges
- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
    [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}


- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    // Log the error
    NSLog(@"### Connection Error");
    // Hide network activity indicator
    [Utils hideNetworkActivityIndicator];
    
    // Notify the delegate
    [connectionDelegate didFailWithError:error];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    NSHTTPURLResponse *_response = (NSHTTPURLResponse *)response;
    statusCode = [_response statusCode];
    data = [NSMutableData new];
    
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)_data {
    [data appendData:_data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    // Log the response
    NSString *responseBody = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
    NSLog(@"### Response with code [%d] and body: %@", statusCode, responseBody);
    
    // Hide network activity indicator
    [Utils hideNetworkActivityIndicator];
    
    // Notify the delegate
    WSResponse *wsResponse = [[WSResponse alloc] initWithStatusCode:statusCode andData:data];
    [connectionDelegate didReceiveResponse:wsResponse];
    
}
@end
